﻿using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ProjectMadaktariMVC.Validators;

namespace ProjectMadaktariMVC.Models
{
    public partial class Patient
    {
        public bool IsValid
        {
            get { return (GetRuleViolations().Count() == 0); }
        }

        public IEnumerable<RuleViolation> GetRuleViolations()
        {

            if (String.IsNullOrEmpty(this.FirstName))
                yield return new RuleViolation("First name required!", "fNameerr");

            if (String.Equals(this.FirstName, "Walsteen"))
                yield return new RuleViolation("Not possible! There are only two in the world!", "fNameerr");

            if (String.IsNullOrEmpty(this.LastName))
                yield return new RuleViolation("Last name required!", "lNameerr");

            if (String.IsNullOrEmpty(this.Gender))
                yield return new RuleViolation("Gender required!", "gendererr");

            if (!this.DateOfBirth.HasValue)
                yield return new RuleViolation("Invalid date of birth!", "dateOfBirtherr");

            if (String.IsNullOrEmpty(this.RegistrationNumber))
                yield return new RuleViolation("Registration number required!", "registrationNumbererr");
            //if (!String.IsNullOrEmpty(this.CellNumber))
            //{
            //    if(!PhoneValidator.IsValid(this.CellNumber))
            //    {
            //        yield return new RuleViolation("Incorrect phone format! Please enter number like 255-755-555-555.", "cellNumbererr");
            //    }
            //}

            yield break;
        }

        partial void OnValidate(ChangeAction action)
        {
            if (!IsValid)
            {
               throw new ApplicationException("Rule violations prevent saving");
            }
        }

        public DateTime GetLastDate()
        {
            DateTime lastDate = DateTime.MaxValue;
            foreach (Episode e in this.Episodes)
            {
                foreach (Procedure p in e.Procedures)
                {
                    if (p.Date < lastDate)
                    {
                        lastDate = (DateTime)p.Date;
                    }
                }
            }
            return lastDate;
        }
    }
}
